package com.lxj.controller;

import com.lxj.domain.SysMenu;
import com.lxj.service.SysMenuService;
import com.lxj.vo.MenuAuth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lxj
 * @date 2021/7/31 9:46
 * @Description:
 */
@Api(tags = "菜单管理")
@RestController
@RequestMapping("sys/menu")
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 加载菜单和权限
     * @return
     */
    @GetMapping("nav")
    @ApiOperation("获取菜单和权限")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public ResponseEntity<MenuAuth> loadMenuAuth(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取当前用户信息
        String userId = authentication.getPrincipal().toString();
        // 查询当前用户的树菜单
        List<SysMenu> menuList = sysMenuService.loadTreeByUserId(userId);
        // 获取当前的权限信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> auths = authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        // 组装对象返回
        MenuAuth menuAuth = new MenuAuth();
        menuAuth.setMenuList(menuList);
        menuAuth.setAuthorities(auths);
        return ResponseEntity.ok(menuAuth);
    }
}
